package com.ld.hpfs.web.controller;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hamcrest.core.IsEqual;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Const;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.dao.UtilMapper;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.ApplyFormService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class ApplyFormController {

	private static final Logger logger = LoggerFactory
			.getLogger(ApplyFormController.class);

	@Autowired
	private ApplyFormService thisService = null;

	@Autowired
    private UtilMapper utilMapper = null;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**
	 * 获取发票申请表单一览数据
	 */
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList01")
	public void getApplyFormList01(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE01");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList02")
	public void getApplyFormList02(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE02");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList03")
	public void getApplyFormList03(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE03");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList04")
	public void getApplyFormList04(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE04");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList05")
	public void getApplyFormList05(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE05");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList06")
	public void getApplyFormList06(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE06");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList07")
	public void getApplyFormList07(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE07");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList08")
	public void getApplyFormList08(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE08");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList09")
	public void getApplyFormList09(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE09");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}
	/**
	 * 获取发票申请表单一览数据
	 */
	@RequestMapping(value = "/getApplyFormList10")
	public void getApplyFormList10(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String returnMsg = getApplyFormList(page, session, request, response, writer, "APPFORM_TYPE10");
		
		logger.debug("{}", returnMsg);
		writer.print(returnMsg);
		writer.flush();
		writer.close();
	}

	
	/**
	 * 获取发票申请表单一览数据
	 * @return 
	 */
	public String getApplyFormList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer, String applyFormType) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		String returnMsg = null;
		String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
		try {
			String formno = request.getParameter("formno") == null ? "" : request.getParameter("formno");
			String custname = request.getParameter("custname") == null ? "" : request.getParameter("custname");
			String formstatus = request.getParameter("formstatus") == null ? "" : request.getParameter("formstatus");
			String applydate = request.getParameter("applydate");
			
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			String companyId = session.getAttribute(
					WebConstants.CURRENT_COMPANY).toString();
			if (user != null) {
				param.put("company_id", companyId);
				param.put("formType", applyFormType);
				
				ArrayList<HashMap<String, Object>> fields = thisService.getApplyFormColumns(param);
				
				String sql = "select * from (select row_number() over (order by FORM_ID) as rn";
				for (int i = 0; i < fields.size(); i++) {
					if (fields.get(i).get("FIELD_NAME").equals("CREATE_TIME")) {
						sql += ", " + "convert(char(10),isnull(" + fields.get(i).get("FIELD_NAME").toString() + ",''),120) as " + fields.get(i).get("FIELD_NAME").toString();
					} else if (fields.get(i).get("FIELD_NAME").equals("SUBMIT_FLAG")) {
						if (lang.equals("en")) {
							sql += ", " + "dbo.func_tax_form_status(SUBMIT_FLAG, 1) as SUBMIT_FLAG";
						} else {
							sql += ", " + "dbo.func_tax_form_status(SUBMIT_FLAG, 0) as SUBMIT_FLAG";
						}
					} else if (fields.get(i).get("FIELD_NAME").equals("CREATE_USER")) {
						sql += ", " + "(select USER_NAME FROM HPFS_C_USER WHERE USER_HID = " + fields.get(i).get("FIELD_NAME") + ") AS CREATE_USER";
					} else {
						sql += ", " + fields.get(i).get("FIELD_NAME").toString();
					}
				}
				int page1 = page.getStart() + page.getLimit();
				sql += ", SUBMIT_FLAG AS sustatus, CTRL11_02 as cust_name from TAX_INVOICE_APPLY_MDATA) t where COMPANY_ID = " + companyId + " AND rn > " + page.getStart()
						 + " and rn <= " + page1 + " and FORM_TYPE = " + "'" + applyFormType + "'";
				
				if (!Tools.isEmpty(formno)) {
					sql += " and FORM_NO = '" + formno + "'";
				}
				if (!Tools.isEmpty(formstatus)) {
					sql += " and sustatus = " + formstatus;
				}
				if (!Tools.isEmpty(custname)) {
					sql += " and cust_name like '%" + custname + "%'";
				}
				if (!Tools.isEmpty(applydate)) {
					applydate = applydate.substring(0, 10);
					sql += " and CREATE_TIME = '" + applydate + "'";
				}
				param.put("sql", sql);
				ArrayList<HashMap<String, Object>> logs = thisService
						.getApplyFormList(param);
				if (logs != null && logs.size() > 0) { 
					result.put("success", true);
					result.put("total", logs.size());
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				returnMsg = JackJson.fromObjectToJson(result);
			} else {
				return "";
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		}
		return returnMsg;
	}
	
	/**
	 * 获取自定义表单一览列
	 */
	@RequestMapping(value = "/getApplyFormColumns")
	public void getApplyFormColumns(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> params = new HashMap<String, Object>();
			String formType = request.getParameter("formType");
			String company_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			if (!Tools.isEmpty(formType)) {
				params.put("formType", formType);
				params.put("company_id", company_id);
				result = thisService.getApplyFormColumns(params);
				
				String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
				StringBuffer returnMsg = new StringBuffer();
				StringBuffer columns = new StringBuffer();
				//一览索引
				columns.append("{'columns': [");
				
				String fie = "";
				if (lang.equals("en")) {
					fie = "FIELD_EN";
				} else {
					fie = "FIELD_CN";
				}
				for (int i = 0; i < result.size(); i++) {
					if(i > 0){
						columns.append(",");
					}
					columns.append("{header: '" + result.get(i).get(fie) + "',align : 'center',dataIndex: '" + result.get(i).get("FIELD_NAME") + "'}");
				}
				
				columns.append("],'success':true}");
				
				returnMsg.append(columns);
				JackJson.fromObjectToJson(returnMsg);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 删除自定义表单数据
	 */
	@RequestMapping(value = "/deleteApplyFormList", method = RequestMethod.POST)
	public void deleteApplyFormList(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {

		String formId = request.getParameter("formId");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		response.setContentType("text/plain;charset=UTF-8");
		String[] formIdlist = formId.split(",");
		try {
			if (user != null) {
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				for (int i = 0; i < formIdlist.length; i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("formId", formIdlist[i]);
					list.add(map);
				}
				param.put("formId", list);

				int ret;
				ret = thisService.deleteApplyFormList(param);
				result.put("resultcode", ret);
				writer.print(JackJson.fromObjectToJson(result));
			}
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 获取下拉框数据
	 * 
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 */
	@RequestMapping(value = "/getTaxCommonData")
	public void getTaxCommonData(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, ArrayList<HashMap<String, Object>>> result = thisService
					.getTaxCommonData();
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 获取表单数据处理
	 */
	@RequestMapping(value = "/getApplyForm", method = RequestMethod.POST)
	public void getApplyForm(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, Object> result = null;
			HashMap<String, Object> params = new HashMap<String, Object>();
			String formId = request.getParameter("formId");
			String returnMsg = "";
			if (formId != null && formId.length() > 0) {
				params.put("formId", formId);
				result = thisService.getApplyForm(params);
				if (result == null || result.size() <= 0) {
					result = new HashMap<String, Object>();
					result.put("retCode", false);
				} else {
					result.put("retCode", true);
				}
				returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 获取表单发票一览数据处理
	 */
	@RequestMapping(value = "/getApplyFormInvoiceList")
	public void getApplyFormInvoiceList(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> params = new HashMap<String, Object>();
			String formId = request.getParameter("formId");
			String returnMsg = "";
			if (!Tools.isEmpty(formId)) {
				params.put("formId", formId);
				result = thisService.getApplyFormInvoiceList(params);
				returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 获取表单营业税发票一览数据处理
	 */
	@RequestMapping(value = "/getApplyFormInvoiceTaxList")
	public void getApplyFormInvoiceTaxList(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> params = new HashMap<String, Object>();
			String formId = request.getParameter("formId");
			String returnMsg = "";
			if (!Tools.isEmpty(formId)) {
				params.put("formId", formId);
				result = thisService.getApplyFormInvoiceTaxList(params);
				returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 保存处理(更新，插入) 保存并新建处理（保存好后清空页面信息）
	 */
	@RequestMapping(value = "/saveApplyForm", method = RequestMethod.POST)
	@SuppressWarnings("unchecked")
	public void saveApplyForm(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, Object> result = new HashMap<String, Object>();
			String returnMsg = "";
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user == null) {
				result.put("retCode", false);// 无用户登录
				returnMsg = JackJson.fromObjectToJson(result);
				writer.print(returnMsg);
				return;
			}
			String json = request.getParameter("data");
			HashMap<String, Object> mapParams = JackJson.fromJsonToObject(json, HashMap.class);
			int companyId = Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			mapParams.put("createUser", user.getUserId());
			mapParams.put("companyId", companyId);
			// 如果是插入返回插入的表单Id，如果是更新则返回更新条数
			int retValue = thisService.saveApplyForm(mapParams);
			// 0 为插入将插入后的id返回前台
			if ((Integer)mapParams.get("applyFormState") == 0) {
				result.put("formId", retValue);
			} else {
				result.put("formId", mapParams.get("formId"));
			}
			result.put("retCode", retValue);
			returnMsg = JackJson.fromObjectToJson(result);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 提交处理
	 */
	@RequestMapping(value = "/submitApplyForm")
	public void submitApplyForm(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		Connection conn = null;
		try {
			HashMap<String, Object> result = new HashMap<String, Object>();
			int formId = Integer.parseInt(request.getParameter("formId"));
			int companyId = Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			int userId = Integer.parseInt(user.getUserId());
			if (!Tools.isEmpty(formId)) {
				try {
					CallableStatement proc = null;
					conn = jdbcTemplate.getDataSource().getConnection();
					// 调用存储过程
					proc = conn.prepareCall("{ call sp_tax_ir(?,?,?,?,?) }");
					proc.setInt(1, companyId);
					proc.setInt(2, userId);
					proc.setInt(3, formId);
					// 返回值
					proc.registerOutParameter(4, Types.INTEGER);
					proc.registerOutParameter(5, Types.VARCHAR);
					proc.execute();
					// 接收存储过程返回值
					int result_code = proc.getInt(4);
					String resultstr = proc.getString(5);
					
					result.put("result", result_code);
					result.put("retstr", resultstr);
				} catch (Exception e) {
					e.printStackTrace();
					result.put("retCode", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 继续提交处理
	 */
	@RequestMapping(value = "/submitFormContinue")
	public void submitFormContinue(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		Connection conn = null;
		try {
			HashMap<String, Object> result = new HashMap<String, Object>();
			int formId = Integer.parseInt(request.getParameter("formId"));
			int companyId = Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			int userId = Integer.parseInt(user.getUserId());
			if (!Tools.isEmpty(formId)) {
				try {
					CallableStatement proc = null;
					conn = jdbcTemplate.getDataSource().getConnection();
					// 调用存储过程
					proc = conn.prepareCall("{ call sp_tax_ir_continue(?,?,?,?,?) }");
					proc.setInt(1, companyId);
					proc.setInt(2, userId);
					proc.setInt(3, formId);
					// 返回值
					proc.registerOutParameter(4, Types.INTEGER);
					proc.registerOutParameter(5, Types.VARCHAR);
					proc.execute();
					// 接收存储过程返回值
					int result_code = proc.getInt(4);
					String resultstr = proc.getString(5);
					
					result.put("result", result_code);
					result.put("retstr", resultstr);
				} catch (Exception e) {
					e.printStackTrace();
					result.put("retCode", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 获取
	@RequestMapping(value = "/getSubmitStatus")
	public void getSubmitStatus(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			int formId = Integer.parseInt(request.getParameter("formId"));
			String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
			param.put("formId", formId);
			param.put("lang", lang);
			ArrayList<HashMap<String, Object>> formstatus = thisService.getSubmitStatus(param);
			int submitStatus = Integer.parseInt(formstatus.get(0).get("submitstatus").toString());
			String formStatusStr = formstatus.get(0).get("formStatusStr").toString();
			String form_no = formstatus.get(0).get("form_no").toString();
			String create_user = formstatus.get(0).get("create_user").toString();
			String create_time = formstatus.get(0).get("create_time").toString();
			
			result.put("submitStatus", submitStatus);
			result.put("formStatusStr", formStatusStr);
			result.put("form_no", form_no);
			result.put("create_user", create_user);
			result.put("create_time", create_time);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 撤回IR处理
	 */
	@RequestMapping(value = "/rollBackApplyForm")
	public void rollBackApplyForm(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		Connection conn = null;
		try {
			HashMap<String, Object> result = new HashMap<String, Object>();
			int formId = Integer.parseInt(request.getParameter("formId"));
			int companyId = Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			int userId = Integer.parseInt(user.getUserId());
			if (!Tools.isEmpty(formId)) {
				try {
					CallableStatement proc = null;
					conn = jdbcTemplate.getDataSource().getConnection();
					// 调用存储过程
					proc = conn.prepareCall("{ call sp_tax_revocation(?,?,?,?,?) }");
					proc.setInt(1, companyId);
					proc.setInt(2, userId);
					proc.setInt(3, formId);
					// 返回值
					proc.registerOutParameter(4, Types.INTEGER);
					proc.registerOutParameter(5, Types.VARCHAR);
					proc.execute();
					// 接收存储过程返回值
					int result_code = proc.getInt(4);
					String resultstr = proc.getString(5);
					
					result.put("result", result_code);
					result.put("retstr", resultstr);
				} catch (Exception e) {
					e.printStackTrace();
					result.put("retCode", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 继续撤回IR处理
	 */
	@RequestMapping(value = "/continueRollBackApplyForm")
	public void continueRollBackApplyForm(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		Connection conn = null;
		try {
			HashMap<String, Object> result = new HashMap<String, Object>();
			int formId = Integer.parseInt(request.getParameter("formId"));
			int companyId = Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			int userId = Integer.parseInt(user.getUserId());
			if (!Tools.isEmpty(formId)) {
				try {
					CallableStatement proc = null;
					conn = jdbcTemplate.getDataSource().getConnection();
					// 调用存储过程
					proc = conn.prepareCall("{ call sp_tax_continue_revocation(?,?,?,?,?) }");
					proc.setInt(1, companyId);
					proc.setInt(2, userId);
					proc.setInt(3, formId);
					// 返回值
					proc.registerOutParameter(4, Types.INTEGER);
					proc.registerOutParameter(5, Types.VARCHAR);
					proc.execute();
					// 接收存储过程返回值
					int result_code = proc.getInt(4);
					String resultstr = proc.getString(5);
					
					result.put("result", result_code);
					result.put("retstr", resultstr);
				} catch (Exception e) {
					e.printStackTrace();
					result.put("retCode", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 多文件上传<br>
	 * 上传的路径是:\basePath\公司编号\表单Id\文件名<br>
	 * 
	 * <ul>
	 * 考虑到：当时更新状态时候:
	 * <li>1.只修改已经上传文件remark</li>
	 * <li>2.上传一个文件并设定remark</li><br>
	 * 两种情况都要处理<br>
	 * </ul>
	 * @param session
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadApplyformAttacheFile", method = RequestMethod.POST)
	public void uploadApplyformAttacheFile(
			HttpSession session, HttpServletResponse response,
			HttpServletRequest request, PrintWriter writer) throws IOException {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try{
			// 获取上传文件目录位置
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			String formId = request.getParameter("formId");
			String basePath = getFileUploadPath(companyId, formId);
			
			// 获取MultipartHttpServletRequest对象
			MultipartHttpServletRequest rq = null;
			if(request instanceof MultipartHttpServletRequest){
				rq = (MultipartHttpServletRequest)request;
			} else {
				MultipartResolver resover = new CommonsMultipartResolver(session.getServletContext());
				rq = resover.resolveMultipart(request);
			}
			// ============ 文件上传处理 =================
			HashMap<String, Object> insertParams = new HashMap<String, Object>();
			HashMap<String, Object> updateParams = new HashMap<String, Object>();
			List<HashMap<String, Object>> insertList = new ArrayList<HashMap<String, Object>>();
			List<HashMap<String, Object>> updateList = new ArrayList<HashMap<String, Object>>();
			List<String> errFileList = new ArrayList<String>();
			
			String user = ((User) session.getAttribute(WebConstants.CURRENT_USER)).getUserId();
			insertParams.put("formId", formId);
			insertParams.put("createUser", user);
			updateParams.put("formId", formId);
			updateParams.put("createUser", user);
			
			// 循环获取MultipartFile
			Iterator<String> it = rq.getFileNames();
			MultipartFile file = null;
			int index = 0;
			while(it.hasNext()){
				index++;
				HashMap<String, Object> insertMap = new HashMap<String, Object>();
				HashMap<String, Object> updateMap = new HashMap<String, Object>();
				String key = it.next();
				file = rq.getFile(key);
				String fileName = "";
				// 更新remark处理或者有新上传并设定remark
				String attacheFileId = request.getParameter("attacheFileId" + index);
				// 当前上传容器没有上传（可能是已经上传过的）
				if(file.isEmpty()){
					// 已经上传，就更新remark
					if(attacheFileId != null){
						String remark = request.getParameter("remark" + index);
						updateMap.put("remark", remark);
						updateMap.put("attacheFileId", attacheFileId);
						updateList.add(updateMap);
					}
					continue;
				} else {
					// 当前上传容器为新上传
					fileName = file.getOriginalFilename();
					String remark = request.getParameter("remark" + index);
					insertMap.put("remark", remark);
					insertMap.put("attacheFile", fileName);
				}
				try{
					File targetFile = new File(basePath, fileName);
					if(targetFile.isDirectory()){
						errFileList.add(fileName);
						continue;
					}
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					// 保存
					file.transferTo(targetFile);
					// 只有上传成功的文件才登陆到DB中
					insertList.add(insertMap);
				} catch(Exception e) {
					errFileList.add(fileName);
				}
			}
			// ============ DB保存处理 =================
			// 文件新上传处理
			if(insertList != null && insertList.size() > 0){
				insertParams.put("applyFormAttacheFile", insertList);
				thisService.insertApplyFormAttacheFile(insertParams);
			}
			// 文件已经上传，只修改remark处理
			if(updateList != null && updateList.size() > 0){
				updateParams.put("applyFormAttacheFile", updateList);
				thisService.updateApplyFormAttacheFile(updateParams);
			}
			if(errFileList.size() > 0){
				result.put("success", false);
				result.put("errors", errFileList);
			}else{
				result.put("success", true);
				result.put("errors", errFileList);
			}
		} catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
        	String returnMsg = JackJson.fromObjectToJson(result);
        	writer.print(returnMsg);
            writer.flush();
            writer.close();
        }
	}

	/**
	 * 上传文件删除
	 * 删除的路径是:\basePath\公司编号\表单Id\文件名<br>
	 * @param session
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/deleteApplyformAttacheFile")
	public void deleteApplyformAttacheFile(HttpSession session, HttpServletResponse response,
			HttpServletRequest request, PrintWriter writer) throws IOException {
		response.setContentType("text/plain;charset=UTF-8");
		// =========== 文件删除 ===========
		// 获取上传文件目录位置
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		String formId = request.getParameter("formId");
		String basePath = getFileUploadPath(companyId, formId);
		String attacheFileName = request.getParameter("attacheFileName");
		File targetFile = new File(basePath, attacheFileName);
		if(targetFile.exists()){
			targetFile.delete();
		}
		//  ===========DB数据删除  =========
		String attacheFileId = request.getParameter("attacheFileId");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("formId", formId);
		params.put("attacheFileId", attacheFileId);
		thisService.deleteApplyFormAttacheFile(params);
		result.put("success", true);
		writer.print(JackJson.fromObjectToJson(result));
		writer.flush();
		writer.close();
	}

	/**
	 * 上传文件下载
	 * 下载的路径是:\basePath\公司编号\表单Id\文件名<br>
	 * 
	 * @param session
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/getApplyformAttacheFilePath")
	public void getApplyformAttacheFilePath(HttpSession session, HttpServletResponse response,
			HttpServletRequest request, PrintWriter writer) throws IOException {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try{
			// =========== 文件删除 ===========
			// 获取上传文件目录位置
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			String formId = request.getParameter("formId");
			String basePath = getFileUploadPath(companyId, formId);
			String attacheFileName = request.getParameter("attacheFileName");
			File targetFile = new File(basePath, attacheFileName);
			if(targetFile.exists()){
				result.put("success", true);
				result.put("filePath", Const.CONTENT_PATH + getFileRelationPath(companyId, formId) + attacheFileName);
			} else {
				result.put("success", false);
			}
		} catch (Exception e){
			logger.error("Exception: {}", e);
		} finally {
			writer.print(JackJson.fromObjectToJson(result));
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 上传文件下载
	 * 下载的路径是:\basePath\公司编号\表单Id\文件名<br>
	 * 
	 * @param session
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/downloadApplyformAttacheFile")
	public void downloadApplyformAttacheFile(HttpSession session, HttpServletResponse response,
			HttpServletRequest request, PrintWriter writer) throws IOException {
		try{
			// =========== 文件删除 ===========
			// 获取上传文件目录位置
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			String formId = request.getParameter("formId");
			String basePath = getFileUploadPath(companyId, formId);
			String attacheFileName = request.getParameter("attacheFileName");
			String fileName = URLDecoder.decode(attacheFileName, "UTF-8");
			File targetFile = new File(basePath, fileName);
			
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1"));  
			response.addHeader("Content-Length", "" + targetFile.length());
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream os = new BufferedOutputStream(response.getOutputStream());
			FileInputStream fis = new FileInputStream(targetFile);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 4];
			int len = 0;
			while((len = fis.read(buffer)) != -1){
				baos.write(buffer, 0, len);
			}
			os.write(baos.toByteArray());
			os.flush();
			os.close();
			fis.close();
		} catch (Exception e){
			logger.error("Exception: {}", e);
		}
	}
	
	/**
	 * 获取上传文件目录位置
	 * 
	 * @param companyId 上传文件公司目录
	 * @param formId 上传文件表单Id
	 * @return
	 */
	private String getFileUploadPath(String companyId, String formId){
		// 设置basePath
		String basePath = null;
		// 获得执行包路径
		String strfilePath = null;
		String strPath = Const.REAL_PATH;
		int pos = strPath.indexOf("tomcat-7.0");
		if(pos <= 0){
			strfilePath = strPath;
		} else {
			strfilePath = strPath.substring(0, strPath.indexOf("tomcat-7.0"));
		}
		
		// 获取license保存路径
		basePath = strfilePath + getFileRelationPath(companyId, formId);
		return basePath;
	}
	
	/**
	 * 获取文件相对上下文环境目录位置
	 * 
	 * @param companyId 上传文件公司目录
	 * @param formId 上传文件表单Id
	 * @return
	 */
	private String getFileRelationPath(String companyId, String formId){
		String relationPath = "/upload/" + companyId + "/" + formId + "/";
		return relationPath;
	}
	
	/**
	 * 客户信息一览取得
	 * 
	 * @param page 分页控件对象
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 * 
	 * @deprecated 直接调用MdataClient的Control了
	 */
	@RequestMapping(value = "/getMdataCustomerList")
	@ResponseBody
	public void getMdataCustomerList(ExtPager page,HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 用于返回的结果集
			HashMap<String, Object> result = new HashMap<String, Object>();
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
			if (currentCompany == null) {
				return;
			}
			int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
			int pageStart = page.getStart();
			int pageEnd = page.getStart() + page.getLimit();
			String orderby = "CUST_ID";
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("pageStart", pageStart);
			params.put("pageEnd", pageEnd);
			params.put("orderBy", orderby);
			params.put("groupId", groupId);

			ArrayList<HashMap<String, Object>> customerList = thisService.getMdataCustomerList(params);
			// 准备前台所需的各种数据
			if (customerList != null && customerList.size() > 0) {
				result.put("success", true);
				result.put("total", params.get("pageCount"));
				result.put("data", customerList);
			} else {
				result.put("success", true);
				result.put("total", params.get("pageCount"));
				result.put("data", "");
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 客户信息详细取得
	 * 
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 */
	@RequestMapping(value = "/getMdataCustomerDetail")
	@ResponseBody
	public void getMdataCustomerDetail(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 用于返回的结果集
			String customerId = request.getParameter("customerId");
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("customerId", customerId);
			HashMap<String, Object> result = thisService.getMdataCustomerDetail(params);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 收件人信息一览取得
	 * 
	 * @param page 分页控件对象
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 * 
	 * @deprecated 直接调用MdataClient的Control了
	 */
	@RequestMapping(value = "/getMdataCustomerAddrList")
	@ResponseBody
	public void getMdataCustomerAddrList(ExtPager page,
			HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
			if (currentCompany == null) {
				return;
			}
			String mainId = request.getParameter("mainId");
			mainId = (mainId == null) ? "" : mainId;
			int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany.toString()));
			int pageStart = page.getStart();
			int pageEnd = page.getStart() + page.getLimit();
			String orderby = "CONTACT_ID";

			HashMap<String, Object> params = new HashMap<String, Object>();
			HashMap<String, Object> result = new HashMap<String, Object>();
			params.put("pageStart", pageStart);
			params.put("pageEnd", pageEnd);
			params.put("orderBy", orderby);
			params.put("groupId", groupId);
			params.put("mainId", mainId);

			ArrayList<HashMap<String, Object>> customerAddrList = thisService.getMdataCustomerAddrList(params);
			// 准备前台所需的各种数据
			if (customerAddrList != null && customerAddrList.size() > 0) {
				result.put("success", true);
				result.put("total", params.get("pageCount"));
				result.put("data", customerAddrList);
			} else {
				result.put("success", true);
				result.put("total", params.get("pageCount"));
				result.put("data", "");
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 收件人详细取得
	 * 
	 * @param session
	 * @param request
	 * @param response
	 * @param writer
	 */
	@RequestMapping(value = "/getMdataCustomerAddrDetail")
	@ResponseBody
	public void getMdataCustomerAddrDetail(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 用于返回的结果集
			String contactId = request.getParameter("contactId");
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("contactId", contactId);
			HashMap<String, Object> result = thisService.getMdataCustomerAddrDetail(params);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 获取提交状态
	 */
	@RequestMapping(value = "/getSubFlag")
	@ResponseBody
	public void getSubFlag(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 用于返回的结果集
			String formId = request.getParameter("formId");
			HashMap<String, Object> params = new HashMap<String, Object>();
			String[] formIdlist = formId.split(",");
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			for (int i = 0; i < formIdlist.length; i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("formId", formIdlist[i]);
				list.add(map);
			}
			params.put("formId", list);
			ArrayList<HashMap<String, Object>> result = thisService.getSubFlag(params);
			int flag = 0;
			for (int i = 0; i < result.size(); i++) {
				if (Integer.parseInt(result.get(i).get("SUBMIT_FLAG").toString()) != 0) {
					flag = 1;
					break;
				}
			}
			HashMap<String, Object> returnMsg = new HashMap<String, Object>();
			returnMsg.put("resultcode", flag);
			logger.debug("{}", returnMsg);
			writer.print(JackJson.fromObjectToJson(returnMsg));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 设置剪切板
	 */
	@RequestMapping(value = "/setClipboardText")
	@ResponseBody
	public void setClipboardText(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> returnMsg = new HashMap<String, Object>();
		try {
			// 用于返回的结果集
			String error_msg = request.getParameter("error_msg");
			try {
				Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
				Transferable t = new StringSelection(error_msg);
				cb.setContents(t, null);
				returnMsg.put("resultcode", 0);
			} catch (Exception e) {
				returnMsg.put("resultcode", 1);
				System.out.println(e);
			}
			logger.debug("{}", returnMsg);
			writer.print(JackJson.fromObjectToJson(returnMsg));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 获取表单一览表单号下拉数据
	 * @formtype 表单类型
	 */
	@RequestMapping(value = "/getFormListFormNo")
	@ResponseBody
	public void getFormListFormNo(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 表单类型
			String formtype = request.getParameter("formtype");
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("formtype", formtype);
			
			ArrayList<HashMap<String, Object>> result = thisService.getFormListFormNo(params);
			
			logger.debug("{}", result);
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 获取表单一览客户名称下拉数据
	 * @formtype 表单类型
	 */
	@RequestMapping(value = "/getFormListCustName")
	@ResponseBody
	public void getFormListCustName(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 表单类型
			String formtype = request.getParameter("formtype");
			String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("lang", lang);
			params.put("formtype", formtype);
			
			ArrayList<HashMap<String, Object>> result = thisService.getFormListCustName(params);
			
			logger.debug("{}", result);
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 获取表单一览表单状态下拉数据
	 * @formtype 表单类型
	 */
	@RequestMapping(value = "/getFormListFormStatus")
	@ResponseBody
	public void getFormListFormStatus(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		try {
			// 表单类型
			String formtype = request.getParameter("formtype");
			String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
			if (lang.equals("en")) {
				lang = "1";
			} else {
				lang = "0";
			}
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("formtype", formtype);
			params.put("lang", lang);
			
			ArrayList<HashMap<String, Object>> result = thisService.getFormListFormStatus(params);
			
			logger.debug("{}", result);
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
}
